package com.dlz.systemshop.filter;

import com.alibaba.fastjson.JSON;
import com.dlz.systemshop.pojo.LogUser;
import com.dlz.systemshop.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author 董熠涛
 * @date 2025/4/26 11:33
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/login")){
            filterChain.doFilter(request,response);
            return;
        }
        String jwt = request.getHeader("JWT");
        if (jwt == null){
            throw new RuntimeException("token为空");
        }

        if ( JwtUtils.isTokenExpired(jwt)){
            throw new RuntimeException("token已过期");
        }

        String jwtfromredis = stringRedisTemplate.opsForValue().get("token_" + jwt);

        if (jwtfromredis == null){
            throw new RuntimeException("token已过期");
        }

        String subjectFromToken = JwtUtils.getSubjectFromToken(jwt);
        LogUser logUser = JSON.parseObject(subjectFromToken, LogUser.class);

        System.out.println(logUser.getAuthorities());

//        当前请求已经经过认证，且认证状态是有效的。
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(logUser,null,logUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);
    }
}
